package com.meiyuetao.myt.pub.web.action;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.util.ExtStringUtils;
import lab.s2jh.core.web.annotation.SecurityControlIgnore;
import lab.s2jh.core.web.captcha.ImageCaptchaServlet;
import lab.s2jh.core.web.view.OperationResult;
import lab.s2jh.web.action.BaseController;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.google.common.collect.Maps;
import com.meiyuetao.myt.customer.service.SsoUserService;
import com.meiyuetao.myt.md.entity.Region;
import com.meiyuetao.myt.md.service.RegionService;
import com.meiyuetao.myt.wlf.entity.WlfAcademyInfo;
import com.meiyuetao.myt.wlf.entity.WlfSDMInfo;
import com.meiyuetao.myt.wlf.entity.WlfSchoolInfo;
import com.meiyuetao.myt.wlf.entity.WlfStudentInfo;
import com.meiyuetao.myt.wlf.entity.WlfUser;
import com.meiyuetao.myt.wlf.service.WlfAcademyInfoService;
import com.meiyuetao.myt.wlf.service.WlfMajorInfoService;
import com.meiyuetao.myt.wlf.service.WlfSDMInfoService;
import com.meiyuetao.myt.wlf.service.WlfSchoolInfoService;
import com.meiyuetao.myt.wlf.service.WlfStudentInfoService;
import com.meiyuetao.myt.wlf.service.WlfUserService;

@MetaData("未来付注册用户管理")
public class WlfUserController extends BaseController<WlfUser, Long> {

    @Autowired
    private WlfUserService wlfUserService;

    @Autowired
    private WlfStudentInfoService wlfStudentInfoService;

    @Autowired
    private WlfSchoolInfoService wlfSchoolInfoService;
    @Autowired
    private WlfMajorInfoService wlfMajorInfoService;
    @Autowired
    private WlfSDMInfoService wlfSDMInfoService;

    @Autowired
    private SsoUserService ssoUserService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private WlfAcademyInfoService wlfAcademyInfoService;

    @Override
    protected BaseService<WlfUser, Long> getEntityService() {
        return wlfUserService;
    }

    @Override
    protected void checkEntityAclPermission(WlfUser entity) {
        // TODO Add acl check code logic
    }

    @MetaData("注册")
    @SecurityControlIgnore
    public HttpHeaders signin() {
        return buildDefaultHttpHeaders("signin");
    }

    @Override
    public HttpHeaders doCreate() {
        Assert.isTrue(bindingEntity.getId() == null);
        WlfStudentInfo studentInfo = (WlfStudentInfo) this.getRequest().getSession().getAttribute("wlfStudentInfo");
        String mobilePhone = (String) this.getRequest().getSession().getAttribute("mobilePhone");
        bindingEntity.setMobilePhone(mobilePhone);
        bindingEntity.setWeilaifuAccount(new BigDecimal(studentInfo.getCredit()));
        bindingEntity.setWeilaifuMaxAccount(new BigDecimal(studentInfo.getCredit()));
        bindingEntity.setRegion(studentInfo.getSchoolInfo().getRegion());
        bindingEntity.setStudentInfo(studentInfo);
        getEntityService().save(bindingEntity);
        this.getRequest().getSession().removeAttribute("wlfStudentInfo");
        this.getRequest().getSession().removeAttribute("SMS_CODE");
        this.getRequest().getSession().removeAttribute("mobilePhone");
        setModel(OperationResult.buildSuccessResult("注册申请成功", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders findWlfStudent() {
        HttpServletRequest request = this.getRequest();
        String idCard = request.getParameter("idCard");
        String loginid = request.getParameter("loginid");
        String trueName = request.getParameter("trueName");
        String schoolId = request.getParameter("schoolId");
        String majorId = request.getParameter("majorId");
        String academyId = request.getParameter("academyId");
        String eduLevel = request.getParameter("eduLevel");
        String degreeCategory = request.getParameter("degreeCategory");
        String degreeMode = request.getParameter("degreeMode");

        // 510199201011234 北大金融
        // 510199201011235 北大世界史
        // 510199201011236 西安信息
        String smsCode = (String) request.getSession().getAttribute("SMS_CODE");
        String checkCode = request.getParameter("checkCode");
        if (!checkCode.equals(smsCode)) {
            setModel(OperationResult.buildFailureResult("手机校验码有误"));
            return buildDefaultHttpHeaders();
        }

        if (wlfUserService.findByProperty("idCard", idCard) != null) {
            setModel(OperationResult.buildFailureResult("身份证号已被注册，请直接登录或询问客服"));
            return buildDefaultHttpHeaders();
        }

        WlfStudentInfo wlfStudentInfo = new WlfStudentInfo();
        wlfStudentInfo.setIdCard(idCard);
        wlfStudentInfo.setTrueName(trueName);
        wlfStudentInfo.setSchoolInfo(wlfSchoolInfoService.findOne(Long.valueOf(schoolId)));
        wlfStudentInfo.setMajorInfo(wlfMajorInfoService.findOne(Long.valueOf(majorId)));
        wlfStudentInfo.setAcademyInfo(wlfAcademyInfoService.findOne(Long.valueOf(academyId)));
        wlfStudentInfo.setEduLevel(eduLevel);
        wlfStudentInfo.setDegreeCategory(degreeCategory);
        wlfStudentInfo.setDegreeMode(degreeMode);
        Boolean isExist = wlfStudentInfoService.checkWlfStudentInfoByAPI(wlfStudentInfo);
        if (!isExist) {
            setModel(OperationResult.buildFailureResult("未查到您的学籍信息，请检查输入的姓名和身份证号是否有误"));
        } else {
            if (ssoUserService.findByProperty("loginid", loginid) != null) {
                setModel(OperationResult.buildFailureResult("账号已被注册，请重新填写"));
            } else {

                wlfStudentInfo.setCredit(wlfStudentInfoService.calcBaseCredit(wlfStudentInfo));
                request.getSession().setAttribute("wlfStudentInfo", wlfStudentInfo);
                setModel(wlfStudentInfo);
            }
        }
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders checkPhone() {
        String element = this.getParameter("element");
        Assert.notNull(element);
        String value = getRequest().getParameter(element);
        if (!ExtStringUtils.hasChinese(value)) {
            value = ExtStringUtils.encodeUTF8(value);
        }
        if (element.equals("loginid")) {
            if (ssoUserService.findByProperty(element, value) != null) {
                this.setModel(Boolean.FALSE);
                return buildDefaultHttpHeaders();
            } else {
                this.setModel(Boolean.TRUE);
                return buildDefaultHttpHeaders();
            }
        }
        return super.checkUnique();
    }

    public HttpHeaders checkUnique() {
        String element = this.getParameter("element");
        Assert.notNull(element);
        String value = getRequest().getParameter(element);
        if (!ExtStringUtils.hasChinese(value)) {
            value = ExtStringUtils.encodeUTF8(value);
        }
        if (element.equals("loginid")) {
            if (ssoUserService.findByProperty(element, value) != null) {
                this.setModel(Boolean.FALSE);
                return buildDefaultHttpHeaders();
            } else {
                this.setModel(Boolean.TRUE);
                return buildDefaultHttpHeaders();
            }
        }
        return super.checkUnique();
    }

    public HttpHeaders getSmsCheckCode() {
        HttpServletRequest request = this.getRequest();
        if (!ImageCaptchaServlet.validateResponse(request, request.getParameter("jcaptcha"))) {
            setModel(OperationResult.buildFailureResult("验证码有误"));
            return buildDefaultHttpHeaders();
        }
        String smsCode = RandomStringUtils.randomNumeric(6);
        this.getRequest().getSession().setAttribute("SMS_CODE", smsCode);
        String mobilePhone = this.getRequest().getParameter("mobilePhone");
        this.getRequest().getSession().setAttribute("mobilePhone", mobilePhone);
        String content = "未来付校验码：" + smsCode;
        wlfUserService.sendMsg(mobilePhone, content);
        setModel(OperationResult.buildSuccessResult("校验码已发送"));
        setModel(OperationResult.buildSuccessResult(smsCode));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders checkSmsCode() {
        String checkCode = this.getRequest().getParameter("checkCode");
        String smsCode = (String) this.getRequest().getSession().getAttribute("SMS_CODE");
        if (!checkCode.equals(smsCode)) {
            setModel(OperationResult.buildFailureResult("校验码有误"));
        }
        return buildDefaultHttpHeaders();
    }

    public Map<Long, String> getProvinces() {
        Map<Long, String> datas = Maps.newHashMap();
        List<Region> regions = regionService.findRoots();
        for (Region region : regions) {
            datas.put(region.getId(), region.getName());
        }
        return datas;
    }

    public HttpHeaders cities() {
        String parent = this.getParameter("province");
        Map<Long, String> datas = Maps.newHashMap();
        List<Region> regions = regionService.findChildren(regionService.findOne(Long.valueOf(parent)));
        for (Region region : regions) {
            datas.put(region.getId(), region.getName());
        }
        setModel(datas);
        return buildDefaultHttpHeaders();
    }

    public Map<Long, String> getSchoolInfos() {
        Map<Long, String> datas = Maps.newLinkedHashMap();
        try {
            List<WlfSchoolInfo> wlfSchoolInfos = wlfSchoolInfoService.findAll();
            for (WlfSchoolInfo item : wlfSchoolInfos) {
                datas.put(item.getId(), item.getName());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return datas;
    }

    public HttpHeaders academyInfos() {
        String schoolId = this.getParameter("school");
        WlfSchoolInfo school = wlfSchoolInfoService.findOne(Long.valueOf(schoolId));
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "school", school));
        List<WlfSDMInfo> wlfSDMInfos = wlfSDMInfoService.findByFilters(groupPropertyFilter);
        Map<Long, String> datas = Maps.newHashMap();
        for (WlfSDMInfo item : wlfSDMInfos) {
            datas.put(item.getAcademy().getId(), item.getAcademy().getName());
        }

        setModel(datas);
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders majorInfos() {
        String schoolId = this.getParameter("school");
        String academyId = this.getParameter("academy");
        WlfSchoolInfo school = wlfSchoolInfoService.findOne(Long.valueOf(schoolId));
        WlfAcademyInfo academy = wlfAcademyInfoService.findOne(Long.valueOf(academyId));
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "school", school));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "academy", academy));
        List<WlfSDMInfo> wlfSDMInfos = wlfSDMInfoService.findByFilters(groupPropertyFilter);
        Map<Long, String> datas = Maps.newHashMap();
        for (WlfSDMInfo item : wlfSDMInfos) {
            datas.put(item.getMajor().getId(), item.getMajor().getName());
        }
        setModel(datas);
        return buildDefaultHttpHeaders();
    }
}